#!/usr/bin/python
import MySQLdb


# init
#game info
world_id = '11'
gameDB = world_id + '_game'
accountDB = world_id + '_account'

# server info
logicSer = '10.0.0.0'
memberSer = '10.174.96.124'

# user info
dbUser = 'db@' + logicSer
dbPass = ''

queryUser = 'query@' + logicSer
queryPass = ''

memberUser = 'member@' + logicSer
memberPass = ''


# mysql
host = 'localhost'
user = 'root'
password = ''
database = 'mysql'


def execSql(func):
    def _execSql(*args, **kwargs):
        sql = func(*args, **kwargs)
        print sql
        try:
            cursor.execute(sql)
            conn.commit()
            print "Done!"
        except Exception, e:
            print "Erro:", e
            conn.rollback()
    return _execSql


@execSql
def dropTestDB():
    sql = 'DROP DATABASE test'
    return sql


@execSql
def createDB(database):
    sql = 'CREATE DATABASE {}'.format(database)
    return sql

@execSql
def createUser(user, password):
    sql = 'CREATE USER {} IDENTIFIED BY "{}"'.format(user, password)
    return sql


@execSql
def createGrant(user, db, grants):
    sql = 'GRANT {} on {} to {}'.format(grants, db, user)
    return sql


conn = MySQLdb.connect(host=host, user=user, passwd=password, charset='utf8')
cursor = conn.cursor()

createDB(gameDB)
createDB(accountDB)
createUser(dbUser, dbPass)
createUser(queryUser, queryPass)
createUser(memberUser, memberPass)
createGrant(dbUser, gameDB + ".*", 'ALL PRIVILEGES')
createGrant(dbUser, accountDB + ".*", 'ALL PRIVILEGES')
createGrant(queryUser, gameDB + ".*", 'SELECT')
createGrant(queryUser, accountDB + ".*", 'SELECT')
createGrant(memberUser, accountDB + ".*", 'INSERT')
